<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!-- public quote -->
<%@include file="/jsp/comm_css_include.jsp"%>
<!-- zTreeStyle.css -->
<link rel="stylesheet" type="text/css" href="${basePath}/css/zTreeStyle/zTreeStyle/zTreeStyle.css">
<!-- jqgrid-->
<link href="${basePath}/css/plugins/jqgriddemo/css/ui.jqgrid-bootstrap.min.css" rel="stylesheet" />
<link href="${basePath}/js/plugins/chosen/chosen.css?v=${empty cssVersion ? Math.random() : cssVersion }" rel="stylesheet" type="text/css"/>
<!doctype html>
<html>
<head>
<style type="text/css">
	.form-inline{
		overflow: visible;
	}
</style>
</head>
<body class="gray-bg">
	<div class="wrapper wrapper-content animated fadeInRight creditbody">
		 <div class="iboxtitle">
			<span><i class="glyphicon glyphicon-map-marker"></i>&nbsp;系统管理&gt;权限管理&gt;用户管理</span>
			<a href="javascript:void(0)"></a>
		</div>
         <div class="ibox-content">
              <button type="button" class="btn dpbtn_green" onclick="add();">新增</button>
              <button type="button" class="btn dpbtn_blue" onclick="disable();">禁用</button>
              <button type="button" class="btn dpbtn_red" onclick="enable();">启用</button>
              <button type="button" class="btn dpbtn_yellow" onclick="del();">删除</button>
              <button type="button" class="btn dpbtn_grey_default" onclick="passwordreset();">密码重置</button>
              <button type="button" class="btn dpbtn_grey_default" onclick="branchPower();">分配权限</button>
              <button type="button" class="btn dpbtn_grey_default" onclick="branchOrg();">数据范围</button>
             <!--  <button type="button" class="btn dpbtn_grey_default" onclick="loginName();">通知范围</button> -->
          </div>
          <div class="ibox-content">
               <div role="form" class="form-inline">
                   <div class="form-group">
                       <select id="roleIds" name="roleIds" class="select-control" style="width: 200px;" onchange="query();"></select>
                   </div>
                   <div class="form-group">
                       <input type="text" placeholder="请输用户名称" id="loginName" class="form-control">
                   </div>
                   <div class="form-group">
                   		<button class="zhixcx" type="button" onclick="query();">执行查询</button>
                   </div>
               </div>
          </div>
          <div class="ibox-content">	
	          	<div class="jqGrid_wrapper">
		             <table id="table_list_1"></table>
		             <div id="pager_list_1"></div>
	         	</div>
          </div>
	</div>
	
	
	<!-- public quote -->
    <%@include file="/jsp/comm_js_include.jsp"%>
	<%@include file="/jsp/notice_people_choice.jsp"%>
	<!-- jqGrid -->
    <script type="text/javascript" charset="utf-8" src="${basePath}/js/plugins/jqgriddemo/js/jquery.jqGrid.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="${basePath}/js/plugins/jqgriddemo/js/grid.locale-cn.min.js"></script>	
    
	<!--zTreeStyle.js-->
	<script type="text/javascript" src="${basePath}/js/zTreeStyle/jquery.ztree.core.js" charset="utf-8"></script>
	<script type="text/javascript" src="${basePath}/js/zTreeStyle/jquery.ztree.excheck.js" charset="utf-8"></script>
    <script type="text/javascript" charset="utf-8" src="${basePath}/js/plugins/chosen/chosen.jquery.js"></script>
    <script type="text/javascript">
	    jQuery(function($) {  
	    	getData();
	    	getRoleData();
	    });
	    
	    var loginName = function(){
	    	layer.open({
	    	  type: 1,
	    	  title:'选择通知人',
	    	  area: ['410px', '550px'], //宽高
	    	  content: $("#noticeChoice")
	    	})
	    }
	    
	    var getRoleData = function(){
	    	$.dpAjax({
	    		url:'${basePath}/role/getEnableList',
     			data:{},
     			success: function(datas){
     				  var roles = datas.result;
     				  var html = '<option value="">全部角色</option>';
     				  if(roles && roles.length > 0) {
					      for(var i=0;i<roles.length;i++){
					          var role = roles[i];
					          html += '<option value="'+role.replaceId+'">'+role.roleName+'</option>';
					      }
     				  }
				     $("#roleIds").html(html);
				     $("#roleIds").chosen();
					  return;
                 }
 	    	});
	    }
	    
	    var updateLayer;
	    var getData = function()
	    {
   	   	   winWidth = $(window).width();
   	   	   winHeight = document.body.offsetHeight - 400;
  		   var win = winWidth / 7 - 20;
  		
  	 	   $.jgrid.defaults.styleUI = 'Bootstrap';
  	 	   
		  jQuery("#table_list_1").jqGrid
		  ({
			url:'${basePath}/user/getMuliList',
	        datatype : "json",
	        colNames : ['主键','人员类型','登录名称', '真实姓名', '角色名称', '手机','职位编号','账号类型', '邮箱','状态码','状态'],
	        colModel : [  
						 {name: 'replaceId', index: 'U.id', hidden:true},
						 {name: 'accountType', index: 'U.accountType', hidden:true},
	                     {name: 'loginName',index: 'U.loginName',width: 100,align: "center"},
	                  	 {name: 'uname',index: 'U.uname',width: 80,align: "center"},
	                  	 {name: 'roleName',index: 'R.roleName',width: 80,align: "center",sortable:false},
	               		 {name: 'phone',index: 'U.phone',width: 80,align: "center"},
	               		 {name: 'positionId',index: 'U.positionId',width: 80,align: "center"},
	            		 {name: 'accountTypeDisplay',index: 'U.accountType',width: 100,align: "center"},
	            		 {name: 'mailbox',index: 'U.mailbox',width: 100,align: "center"},
	            		 {name: 'dpStatus', index: 'U.dpStatus', hidden:true},
	            		 {name: 'dpStatusDisplay',index: 'U.dpStatus',width: 80,align: "center",
	            			 formatter: function (cellvalue, options, rowObject) 
	            			 {
	            				 var dpStatus = rowObject.dpStatus;
	            				 if(dpStatus == 1)
	            				 {
	            					 return '<span style="color: green;">' + cellvalue + '</span>';
	            				 }
	            				 
	            				 if(dpStatus == 2)
	            				 {
	            					 return '<span style="color:#FC1515;">' + cellvalue + '</span>';
	            				 }
	            			 }	 
	            		 } 
	                   ],
              mtype : "post",
              height: winHeight,
              autowidth: true,
              shrinkToFit: true,
              rowNum: 15,
              rowList: [30, 60, 90,120,150],
              viewrecords: true,
              pager: "#pager_list_1",
              hidegrid: false,
              sortorder : "desc",
              sortname : 'created',
              multiselect : true,
              altRows:true,
              altclass:'someClass',
              ondblClickRow:function(rowId,v,e)
              {
            	  var rowData = $("#table_list_1").jqGrid("getRowData", rowId);
            	  var id = rowData.replaceId;
            	  updateLayer =  layer.open({
    		    	  type: 2,
    		    	  title: '修改用户',
    		    	  shadeClose: true,
    		    	  shade: 0.8,
    		    	  area: ['800px', '65%'],
    		    	  content: '${basePath}/user/toUpdate?uid='+id,
    		    	  end: function () 
    		    	  {
    		    		  refresh();
    		          }
    	    	});  	  
              },
              jsonReader : {
            	  root:"result.rows",
            	  page: "result.page",
            	  total: "result.total",
            	  records: "result.records",
            	  repeatitems: false,
            	  id: "replaceId" 
              },
              loadComplete:function(datas){
	         	  if (datas.flag == "100100") {
	                   layer.msg("查询成功!", {icon: 6, time: 1000});
	                   return;
	               }
	         	  if(datas.flag == '100802') {
	 				  top.location.href = thisLoginUrl;
	 				  return;
	 			  }

	         	  layer.msg(datas.message, {icon: 2});
	           }
	      });
	    }	    
	    
	    window.onresize = function()
	    {
	    	$("#table_list_1").setGridWidth($(window).width()-80);
	    }
	    
	    var query = function()
	    {
	    	var postData = $("#table_list_1").jqGrid("getGridParam", "postData");
	    	var loginName = document.getElementById('loginName').value || '';
	    	var roleIds = document.getElementById('roleIds').value || '';
	    	$.extend(postData, { loginName : loginName.trim(), roleIds : roleIds.trim()});
	    	refresh();
	    }
	    
	    
	    var index = 0;
	    var branchPower = function() {
	    	var rowData = jQuery('#table_list_1').jqGrid('getGridParam','selarrrow');  
	    	if(rowData.length < 1)
	    	{  
	    		layer.msg("请选择要分配的用户数据！", {icon: 5});
				return;
	    	}
	    	
	    	if(rowData.length > 1)
	    	{
	    		layer.msg("只能选择一个用户分配！", {icon: 5});
				return;
	    	}
			var userId = $('#table_list_1').jqGrid('getGridParam','selarrrow').join(",");
			 $.dpAjax({
	    		url:'${basePath}/role/queryTree',
    			data:{
    				"userId":userId
    			},
    			success: function(datas){
	    			  if(datas.flag == "100100")
					  {
	    				  var content = '<div class="ibox-content" style="height: 480px;border: 1px solid #F5F5F6; overflow:auto;overflow-x: hidden;">'
		    					+ '	<div id="treeDemo" class="ztree">&nbsp;</div>'
		    				+ '</div>'
		    				+ '<div class="ibox-content">'
		    				+ '	 <button class="btn dpbtn_green" type="button" onclick="confirmRole();">确定</button>'
		    				+ '	 <button class="btn dpbtn_red" type="button" onclick="cancelRole();">取消</button>'
		    				+ '</div>';
		    		
					    	index = layer.open({
						    	  title:'分配权限列表',
						    	  type: 1,
						    	  area: ['800px', '600px'], //宽高
						    	  content: content
						    });
					    				
						    var setting = {
									check: {
										enable: true
									},
									data: {
										simpleData: {
											enable: true
										}
									}
						    };			
						  for(var i=0; i<datas.result.length;i++){
							  datas.result[i].open = false;
						  }
	    				  var zNodes = datas.result;
	    				  $.fn.zTree.init($("#treeDemo"), setting, zNodes);
						  return;
					  }
					  if(datas.flag == "100200")
	                  {
						  $.fn.showDatas({"datas":datas});
	                	  return;
	                  }
					  layer.msg(datas.message, {icon: 2});
                }
	    	});
	    }
	    
	    var cancelRole = function()
	    {
	    	layer.close(index);
	    }

	    
	    var confirmRole = function()
	    {
	    	 var zTree = $.fn.zTree.getZTreeObj("treeDemo"); 
	    	 var nodes = zTree.getCheckedNodes(true);
	    	 
	    	 if(nodes.length == 0)
	    	 {
	    		 layer.msg("请选择要分配的用户数据！", {icon: 5});
				 return;
	    	 }
	    	 
	    	 var roleId = "";
	    	 
	    	 for(var i=0;i<nodes.length;i++)
	    	 {
	    		 roleId += nodes[i].id + ",";
	    	 }
	    	 if(roleId != "")
	    	 {
	    		 roleId = roleId.substring(0,roleId.length-1);
	    	 }
	    	 var rowData = jQuery('#table_list_1').jqGrid('getGridParam','selarrrow');  
		     if(rowData.length < 1){return;}
	    	 var uid = $('#table_list_1').jqGrid('getGridParam','selarrrow').join(",");	 
    		 $.dpAjax({
 	    		url:'${basePath}/user/grant',
     			data:{
     				"userId":uid,
     				"roleId":roleId
     			},
     			success: function(datas){
     			  if(datas.flag == "100100")
 					  {
     				 	  layer.msg("分配角色执行成功！", {icon: 6});
     				 	  layer.close(index);
 						  return;
 					  }
 					  if(datas.flag == "100200")
 	                  {
 						  $.fn.showDatas({"datas":datas});
 	                	  return;
 	                  }
 					  layer.msg(datas.message, {icon: 2});
                 }
 	    	});
	    }
	    
		 var zTrees_;
    	 var branchOrg = function(){
    		 
 	    	var rowDataIds = jQuery('#table_list_1').jqGrid('getGridParam','selarrrow');  
 	    	
 	    	if(rowDataIds.length == 0){  
 	    		layer.msg("请选择要分配的用户数据！", {icon: 5});
 				return;
 	    	}
 	    	
 	    	if(rowDataIds.length > 1){
 	    		layer.msg("只能选择一个用户分配！", {icon: 5});
 				return;
 	    	}
 	    	if(rowDataIds[0] == 1) {
 	    		layer.msg("无法更改超级管理员账号！", {icon: 5});
 				return;
 	    	}
 	    	var rowData = $("#table_list_1").getRowData($("#table_list_1").getGridParam("selrow")); 
 	    	
 		    var accountType = rowData.accountType;
 		    
 		    if(accountType == 0){ //业务员
 		    	layer.msg("业务员不能分配数据范围！", {icon: 5});
 				return;
 		    }
 		    var scene = 0; //默认内勤
 		    if(accountType == 2) { //管理员
 		    	scene = 1;
 		    }
 		    
 			$.dpAjax({
 	    		url:'${basePath}/BaseAccountBusiUnitController/mulitList',
 	    		data:{"userId" : rowDataIds[0], "scene" : scene},
     			success: function(datas){
 	    			  if(datas.flag == "100100")
 					  {
 	    				  var content = '<div class="ibox-content" style="height: 480px;border: 1px solid #F5F5F6; overflow:auto;overflow-x: hidden;">'
 		    					+ '	<div id="orgtreeDemo" class="ztree">&nbsp;</div>'
 		    				+ '</div>'
 		    				+ '<div class="ibox-content">'
 		    				+ '	 <button class="btn dpbtn_green" type="button" onclick="confirmOrg();">确定</button>'
 		    				+ '	 <button class="btn dpbtn_red" type="button" onclick="cancelOrg();">取消</button>'
 		    				+ '</div>';
 		    		
 					    	index = layer.open({
 						    	  title:'分配单位',
 						    	  type: 1,
 						    	  area: ['800px', '600px'], //宽高
 						    	  content: content
 						    });
 						    var setting = {
 									check: {
 										enable: true
 									},
 									data: {
 										simpleData: {
 											enable: true
 										},
 									},
 									callback: {
 										onNodeCreated: zTreeOnNodeCreated
 										},
 						    };			
 						  var  arr = [];
 	    				  var d = datas.result.rows;
 	    				  for(var i in d)
 	    				  {  
 	    					  var r = d[i];
 	    					  var objs = {};
 	    					  objs.replaceId = r.replaceId;
 	    					  objs.id = r.orgCode;
 	    					  objs.pId = r.parentCode;
 	    					  objs.name = r.orgName;
 	    					  if(r.parentCode == '0'){
		            		  	 objs.open = true;
	     					  } else {
	     						 objs.open = false; 
	     					  }
 	    					  objs.checked = r.checked;
 		            		  objs.salersman=r.salersman;
 	    					  arr.push(objs);
 	    				  }
 	    				    zTrees_ = $.fn.zTree.init($("#orgtreeDemo"), setting, arr);
 	    				    var rowData = $("#table_list_1").getRowData($("#table_list_1").getGridParam("selrow")); 
 	    			 		var accountType = rowData.accountType;
					        if(accountType == 0){
			 	 		    	zTrees_.setting.check.chkboxType={"Y": "", "N": ""};
			 	 		    } else {
			 	 		    	zTrees_.setting.check.chkboxType={"Y": "", "N": "ps"};
			 	 		    }			
	 					    return;
 					  }
 					  if(datas.flag == "100200")
 	                  {
 						  $.fn.showDatas({"datas":datas});
 	                	  return;
 	                  }
 					  layer.msg(datas.message, {icon: 2});
                 }
 	    	});
 	    }
    	 
    	function zTreeOnNodeCreated(event, treeId, treeNode) {
    		if(treeNode.salersman==true){
    			$('#'+treeNode.tId+'_ico').css("background", "url('../../../img/header.png') center center/15px 15px no-repeat");
    		}
    	}
    	 
		var confirmOrg = function()
	    {
			var treeObj = $.fn.zTree.getZTreeObj("orgtreeDemo");
			var nodes = treeObj.getCheckedNodes(true);
	        var length = nodes.length;
	        if(length == 0) {
	        	layer.msg('请选择分配的节点',{icon:7});
	        	return;
	        }
	        
	        var rowData = $("#table_list_1").getRowData($("#table_list_1").getGridParam("selrow")); 
		    var accountType = rowData.accountType;
	        var idUnit=''; 
			var codeUnit='';
	         if(length == 1) {
				if(accountType == 0 && !nodes[0].salersman){
					 layer.msg("业务员只能选择一个业务员节点", {icon: 5});
            		 return;
		        }
	        	idUnit += nodes[0].replaceId;
	           	codeUnit += nodes[0].id;
	        } else {
	        	if(accountType == 0){
	        		layer.msg("业务员只能选择一个业务员节点", {icon: 5});
	        		return false;
	        	}
				if(nodes.length > 10){
					layer.msg("最多选择10个业务单位", {icon: 5});
           		 	return false;
				}
				for (var i = 0; i < nodes.length; i++) {  
                	 idUnit += nodes[i].replaceId +',';
                	 codeUnit+=nodes[i].id+',';
	            }
				idUnit = idUnit.substring(0,idUnit.lastIndexOf(","));
				codeUnit = codeUnit.substring(0,codeUnit.lastIndexOf(","));
	        }
			
	         var userId = rowData.replaceId;
	         
	         if(userId == ""){
	        	 layer.msg("数据异常，请刷新列表！", {icon: 5});
	        	 return;
	         }
	         
	         $.dpAjax({
		    	url:'${basePath}/BaseAccountBusiUnitController/insertBatch',
	   			data:{
	   				"userId": userId,
	   				"codeUnit":codeUnit,
	   				"idUnit":idUnit
	   			},
	   			success: function(datas){
	   			  if(datas.flag == "100100")
						  {
	   				 	  layer.msg("分配单位/业务员成功！", {icon: 6});
	   				 	  layer.close(index);
							  return;
						  }
						  if(datas.flag == "100200")
		                  {
							  $.fn.showDatas({"datas":datas});
		                	  return;
		                  }
						  layer.msg(datas.message, {icon: 2});
	               }
		    	});
			
	    }
		
		var cancelOrg =function()
	    {
			layer.closeAll();	
	    }
		
		var addlayer;
		
	    var add = function()
	    {
	       
	    	addlayer=layer.open({
		    	  type: 2,
		    	  title: '新增用户',
		    	  shadeClose: true,
		    	  shade: 0.8,
		    	  area: ['800px', '65%'],
		    	  content: '${basePath}/user/toAdd',
		    	  end: function () 
		    	  {
		    		  refresh();
		          }
	    	});
	    }
	    
	    
	    var del = function()
	    {
	    	
	    	var uid = $('#table_list_1').jqGrid('getGridParam','selarrrow').join(",");
	    	if(uid == "" || null == uid)
	    	{
	    		layer.msg("请选择要删除的用户！", {icon: 5});
	    		return;
	    	}
	    	
	    	var uuid = uid.split(",");
	    	
	    	var b = false;
	    	
	    	for(var i=0;i<uuid.length;i++)
	    	{
	    		if(uuid[i] == 1)
	    		{
		    		b = true;
		    		break;
	    		}
	    	}
	    	
	    	if(b)
	    	{
	    		layer.msg("超级管理员不可以删除！", {icon: 5});
	    		return;
	    	}
	    	
	    	layer.confirm('您确认要删除吗？', {
  			  btn: ['确定','取消'] //按钮
  			},function(){
  				layer.closeAll();
  				$.dpAjax({
  	 	    		url:'${basePath}/user/del',
  	     			data:{
  	     				"id":uid
  	     			},
  	     			success: function(datas){
  	     			  if(datas.flag == "100100")
  	 					  {
  	     				 	  layer.msg("删除执行成功！", {icon: 6});
  	     				 	  refresh();
  	 						  return;
  	 					  }
  	 					  if(datas.flag == "100200")
  	 	                  {
  	 						  $.fn.showDatas({"datas":datas});
  	 	                	  return;
  	 	                  }
  	 					  layer.msg(datas.message, {icon: 2});
  	                 }
  	 	    	});
  			});
	    }
	    
	    var disable = function()
	    {
	    	var rowData = jQuery('#table_list_1').jqGrid('getGridParam','selarrrow');  
	    	if(rowData.length < 1)
	    	{  
	    		layer.msg("请选择禁用的用户信息！", {icon: 5});
				return;
	    	}
	    	
	    	var uid = $('#table_list_1').jqGrid('getGridParam','selarrrow').join(",");
	    	
	    	var uuid = uid.split(",");
	    	
	    	var b = false;
	    	
	    	for(var i=0;i<uuid.length;i++)
	    	{
	    		if(uuid[i] == 1)
	    		{
	    			b = true;
	    			break;
	    		}
	    	}
	    	
	    	if(b)
	    	{
	    		layer.msg("超级管理员不可禁用！", {icon: 5});
	    		return;
	    	}
	    	
	    	for(var i=0;i<rowData.length;i++)
	    	{
	    		var dpStatus = jQuery('#table_list_1').jqGrid('getCell',rowData[i],'dpStatus'); 
	    	   	if(dpStatus == 2)
	    	   	{
	    	   		layer.msg("已经禁用的用户不可再次执行！", {icon: 5});
		    		return;
	    	   	}
	    	} 
	    	
	    	
	    	layer.confirm('您确认要禁用吗？', {
	  			  btn: ['确定','取消'] //按钮
  			},function(){
  				layer.closeAll();
  				$.dpAjax({
  	 	    		url:'${basePath}/user/disable',
  	     			data:{
  	     				"id":uid
  	     			},
  	     			success: function(datas){
  	     				layer.msg("禁用执行成功！", {icon: 6});
  	     				refresh();
  	                 }
  	 	    	});
  				
  			});
	    }
	    
	    var enable = function()
	    {
	    	var rowData = jQuery('#table_list_1').jqGrid('getGridParam','selarrrow');  
	    	if(rowData.length < 1)
	    	{  
	    		layer.msg("请选择启用的用户信息！", {icon: 5});
				return;
	    	}
	    	
	    	var uid = $('#table_list_1').jqGrid('getGridParam','selarrrow').join(",");
	    	
	    	var uuid = uid.split(",");
	    	
	    	var b = false;
	    	
	    	for(var i=0;i<uuid.length;i++)
	    	{
	    		if(uuid[i] == 1)
	    		{
	    			b = true;
	    			break;
	    		}
	    	}
	    	
	    	if(b)
	    	{
	    		layer.msg("超级管理员不可再次启用！", {icon: 5});
	    		return;
	    	}
	    	
	    	/* for(var i=0;i<rowData.length;i++)
	    	{
	    		var dpStatus = jQuery('#table_list_1').jqGrid('getCell',rowData[i],'dpStatus'); 
	    	   	if(dpStatus == 1)
	    	   	{
	    	   		layer.msg("已经启用的用户不可再次执行！", {icon: 5});
		    		return;
	    	   	}
	    	}  */
	    	
	    	layer.confirm('您确认要启用吗？', {
	  			  btn: ['确定','取消'] //按钮
			},function(){
				layer.closeAll();
				$.dpAjax({
	 	    		url:'${basePath}/user/enable',
	     			data:{
	     				"id":uid
	     			},
	     			success: function(datas){
	     				 layer.msg("启用执行成功！", {icon: 6});
	     				 refresh();
	                 }
	 	    	});
				
			});
	    	
	    }
	    
	   
	    //密码重置
	    var passwordreset = function()
	    {
	    	var rowData = jQuery('#table_list_1').jqGrid('getGridParam','selarrrow');  
	    	if(rowData.length < 1)
	    	{  
	    		layer.msg("请选择要密码重置的用户！", {icon: 5});
				return;
	    	}
	    	
	    	var uid = $('#table_list_1').jqGrid('getGridParam','selarrrow').join(",");
	    	
	    	layer.confirm('您确认要密码重置吗？', {
	  			  btn: ['确定','取消'] //按钮
			},function(){
				layer.closeAll();
				$.dpAjax({
	 	    		url:'${basePath}/user/reset',
	     			data:{
	     				"id":uid
	     			},
	     			success: function(datas){
	     				 layer.msg("密码重置执行成功！", {icon: 6});
	     				 refresh();
	                 }
	 	    	});
				
			});
	    }
	    
	    var refresh = function()
	    {
	    	$("#table_list_1").jqGrid("setGridParam", { search: true }).trigger("reloadGrid", [{ page: 1}]);
	    }
	    
    </script>
</body>
</html>
